package com.lu.netty.io.core

import io.netty.channel.Channel
import java.io.Closeable
import java.io.IOException

/**
 * FileName : NettyConnector
 * Author : luqihua
 * Date : 2024/11/29
 * Desc :
 **/

class NettyConnector(
    private val channel: Channel
) : IMessageSender, Closeable {

    val key: String = NettyConfigure.createChannelKey(channel)

    override fun send(message: String) {
        NettyLog.d("NettyConnector", "${channel.remoteAddress()}->send: $message")
        if (channel.isActive) {
            channel.writeAndFlush(message)
        }
    }


    override fun close() {
        try {
            channel.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    fun matchChannel(channel: Channel): Boolean {
        return this.channel == channel
    }

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false

        other as NettyConnector

        if (channel != other.channel) return false
        if (key != other.key) return false

        return true
    }

    override fun hashCode(): Int {
        var result = channel.hashCode()
        result = 31 * result + key.hashCode()
        return result
    }


}